package enterprise.manage.service.extremetable;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by IntelliJ IDEA.
 * User: qiaoying
 * Date: 2009-11-5
 * Time: 15:05:11
 * Desc: cookie和session中保存页大小
 */
public class ExtremeRememberPagesizeUtils {
    /**
     * 声明protected的构造方法
     */
    protected ExtremeRememberPagesizeUtils() {
    }

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ExtremeRememberPagesizeUtils.class);
    /**
     * 默认的页大小
     */
    public static final int DEFAULT_PAGESIZE = 20;
    /**
     * cookie存储的 页大小名字
     */
    public static final String COOKIE_PAGESIZE_KEY = "et_ps";
    /**
     * session存储的 页大小名字
     */
    public static final String SESSION_PAGESIZE_KEY = "et_ps";
    /**
     * 默认年大小
     */
    private static final int DEFAULT_YEAR = 365;
    /**
     * 默认天大小
     */
    private static final int DEFAULT_DAY = 24;
    /**
     * 默认小时
     */
    private static final int DEFAULT_HOUR = 60;
    /**
     * 默认分
     */
    private static final int DEFAULT_MINUTE = 60;

    /**
     * 获得默认的页大小，如果cookie的值存在，则取cookie的值
     *
     * @param request HttpServletRequest
     * @return 默认页大小
     */
    public static int getDefaultPagesize(HttpServletRequest request) {
        return getDefaultPagesize(request, DEFAULT_PAGESIZE);
    }

    /**
     * 获得默认的页大小，如果cookie的值存在，则取cookie的值
     *
     * @param request  HttpServletRequest
     * @param pagesize 指定默认页大小
     * @return DefaultPagesize 默认页大小
     */
    public static int getDefaultPagesize(HttpServletRequest request, int pagesize) {
        Integer sessionDefaultPagesize = getSessionDefaultPagesize(request);
        Integer defaultPagesize;
        if (sessionDefaultPagesize != null) {
            defaultPagesize = sessionDefaultPagesize;
        } else {
            defaultPagesize = getCookieDefaultPagesize(request);
        }

        if (defaultPagesize != null) {
            return defaultPagesize;
        } else {
            return pagesize;
        }

    }

    /**
     * 将默认的页大小存入cookie
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param pagesize 页大小
     */
    public static void saveRememberPagesize(HttpServletRequest request
            , HttpServletResponse response, Integer pagesize) {
        //存入session
        if (!pagesize.equals(getSessionDefaultPagesize(request))) {
            request.getSession().setAttribute(SESSION_PAGESIZE_KEY, pagesize);
            LOGGER.debug("设置新的页大小session，值为：{}", pagesize);
        }

        //存入cookie
        if (!pagesize.equals(getCookieDefaultPagesize(request))) {
            //获得path
            String uri = request.getRequestURI();
            uri = uri == null ? "" : uri.replace("\r","\\r").replace("\n","\\n");
            int keyIndex = uri.lastIndexOf("/");
            Cookie cookie = new Cookie(COOKIE_PAGESIZE_KEY, pagesize + "");
            cookie.setPath(uri.substring(0, keyIndex + 1));
            cookie.setMaxAge(DEFAULT_YEAR * DEFAULT_DAY * DEFAULT_HOUR * DEFAULT_MINUTE);
            response.addCookie(cookie);
            LOGGER.debug("设置新的页大小cookie，路径：{}，值为：{}", cookie.getPath(), pagesize);
        }
    }

    /**
     * 从session中获得默认页大小
     *
     * @param request HttpServletRequest
     * @return 默认页大小
     */
    private static Integer getSessionDefaultPagesize(HttpServletRequest request) {
        Integer defaultPagesize = (Integer) request.getSession().getAttribute(SESSION_PAGESIZE_KEY);

        if (defaultPagesize != null) {
            LOGGER.debug("从session中获得默认的分页大小：{}", defaultPagesize);
        }

        return defaultPagesize;
    }

    /**
     * 从session中获得默认页大小
     *
     * @param request HttpServletRequest
     * @return 默认页大小
     */
    private static Integer getCookieDefaultPagesize(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }

        for (Cookie cooky : cookies) {
            if (COOKIE_PAGESIZE_KEY.equalsIgnoreCase(cooky.getName()) && cooky.getValue().matches("^\\d{1,9}$")) {
                LOGGER.debug("从cookie中获得默认的分页大小：{}", cooky.getValue());
                return Integer.parseInt(cooky.getValue());
            }
        }

        return null;
    }
}
